import os
import json
import datetime
from ruamel.yaml import YAML
from jinja2 import Environment, FileSystemLoader
from typing import List, Dict, Any

class ReportGenerator:
    def __init__(self, comparison_data: List[Dict[str, Any]], output_dir: str):
        self.data = comparison_data
        self.output_dir = output_dir
        # Jinja2模板环境设置
        template_path = os.path.join(os.path.dirname(__file__), '..', 'templates')
        print("模板查找路径:", os.path.abspath(template_path))
        self.env = Environment(loader=FileSystemLoader(template_path))

    def generate_json(self) -> str:
        path = os.path.join(self.output_dir, 'comparison_report.json')
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(self.data, f, indent=4, ensure_ascii=False)
        return path

    def generate_yaml(self) -> str:
        path = os.path.join(self.output_dir, 'comparison_report.yaml')
        yaml = YAML()
        with open(path, 'w', encoding='utf-8') as f:
            yaml.dump(self.data, f)
        return path

    def generate_html(self) -> str:
        path = os.path.join(self.output_dir, 'comparison_report.html')
        template = self.env.get_template('report_template.html')
        
        # 为模板准备数据，例如可以增加一些统计信息
        context = {
            'report_time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'results': self.data,
            'total_metrics': len(self.data),
            # TODO: 可以在这里增加更多统计，如性能提升/下降的指标数量等
        }
        
        with open(path, 'w', encoding='utf-8') as f:
            f.write(template.render(context))
        return path

    def generate_all(self) -> List[str]:
        return [
            self.generate_json(),
            self.generate_yaml(),
            self.generate_html(),
        ]
